<?php
// +----------------------------------------------------------------------
// | HkCms 前台留言板处理
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: HkCms team <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\index\controller;

use think\exception\ValidateException;
use think\facade\Db;

class Guestbook extends BaseController
{
    public function index()
    {
        if ($this->request->isPost()) {
            $catid = $this->request->param('catid','','intval');
            $row = $this->request->param('row',[],'stripslashes,strip_tags');
            if (empty($catid) || empty($row)) {
                return '';
            }
            $cate = \app\admin\model\cms\Category::where(['id'=>$catid])->find();
            if (empty($cate)) {
                $this->error(lang('Column doesn\'t exist.'));
            }

            // 获取对应表
            $tablename = Db::name('model')->where(['id'=>$cate['model_id']])->value('tablename');

            // 获取表字段
            $modelField = (new \app\admin\model\cms\ModelFieldBind)->getAllowField($catid, $cate['model_id'], $row);

            list($valData,$msgData) = build_tp_rules($modelField);
            try {
                $this->validate($row, $valData, $msgData);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }

            Db::startTrans();
            try {
                (new \app\admin\model\cms\Guestbook)->setTable($tablename)->save(array_merge($row, [
                    'model_id'=>$cate['model_id'],
                    'category_id'=>$catid,
                    'create_time'=>time()
                ]));
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        } else {
            $this->error(lang('Illegal access'));
        }
    }
}